import { ProForm, ProFormDigit, ProFormInstance, ProFormSelect, ProFormText, ProFormTreeSelect, ProFormRadio } from "@ant-design/pro-components";
import styles from "./index.module.less";
import { map } from "lodash";
import { Button, Space, Modal } from "antd";
import { useRef, useState, forwardRef, useImperativeHandle, useEffect } from "react";
import useUrl from "@/hooks/useUrl";

export type ModelRef = React.Ref<{
    showModel: () => void;
    closeModel: () => void;
}>;

type ColumnItem = {
	label?: string;
	name: string;
	options?: any;
	type: "input" | "select" | "digital" | "password" | "selectTree" | "radioGroup" | "upload";
	rule?: any[];
	[key: string]: any;
};

interface Props {
	columns: ColumnItem | any[];
	onCreate: (value: any, callBack?: () => void) => void;
	children: React.ReactNode;
	title?: string,
	defaultValues?: any
}

export default forwardRef((props: Props, ref: ModelRef) => {
	const { navigate } = useUrl();
	const formRef = useRef<ProFormInstance>();
	const [isShowPeopleDialog, setIsShowPeopleDialog] = useState(false);
	const { columns, onCreate, title, defaultValues } = props;

	useEffect(() => {
		if(defaultValues) {
			formRef.current?.setFieldsValue(defaultValues);
		} else {
			formRef.current?.resetFields();
		}
	}, [defaultValues])

	// 暴露方法给父组件
	useImperativeHandle(ref, () => ({
		showModel() {
			setIsShowPeopleDialog(true);
		},
		closeModel() {
			setIsShowPeopleDialog(false);
		}
	}));

	const handleCreate = () => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(values => {
			onCreate?.(values, () => {
				formRef.current?.resetFields();
			});
		});
	};

	const handleCloseModal = () => {
		setIsShowPeopleDialog(false)
	}

	return (
		<Modal
			title={title || "创建"}
			open={isShowPeopleDialog}
			onOk={handleCreate}
			onCancel={handleCloseModal}
			okText="确定"
			cancelText="关闭"
			centered
		>
			<ProForm submitter={false} formRef={formRef} labelCol={{ span: 4 }} layout="horizontal" className={styles.formContainer}>
				{map(columns, (item: ColumnItem, index: number) => {
					switch (item.type) {
						case "input":
							return <ProFormText {...item} key={index}/>;
						case "password":
							return <ProFormText.Password {...item} key={index} />;
						case "digital":
							return <ProFormDigit {...item} key={index}/>;
						case "select":
							return <ProFormSelect {...item} key={index} />;
						case "selectTree":
							return <ProFormTreeSelect {...item} key={index} />;
						case "radioGroup":
							return <ProFormRadio.Group {...item} key={index} />;
						case "upload":
							return <ProFormRadio.Group {...item} key={index} />;
					}
				})}
				{props.children}
			</ProForm>
		</Modal>
	);
});
